<!--
 * @Description: MQTT 组件
 * @Author: chendingfengmail@163.com
 * @Date: 2022-01-05 08:47:52
 * @LastEditTime: 2022-01-05 13:39:06
 * @LastEditors: chendingfengmail@163.com
 * @Reference: 
-->
<!-- MQTT 组件 -->
<template>
  <div></div>
</template>

<script>
import mqtt from 'mqtt'
import util from '@/libs/util'
export default {
  name: 'dd-mqtt',
  props: {
    // 服务端地址
    service: {
      type: String,
      default: () => {
        return '';
      },
    },
    // 连接用户名
    username: {
      type: String,
      default: () => {
        return '';
      }
    },
    // 连接密码
    password: {
      type: String,
      default: () => {
        return '';
      }
    },
    // 订阅主题
    topic: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
    };
  },

  components: {},

  computed: {},

  mounted() { 
    this.mqttController(this.service, this.username, this.password, this.topic, false)
  },

  methods: {
    mqttController(service, username, password, topic, disconnect) {
      const clientOptions = {
        connectTimeout: 40000,
        clientId: `MQTT_WEB_CLIENT_${util.generateUUID()}`,
        username: username,
        password: password,
        clean: false
      }
      let mqttClient = mqtt.connect(service, clientOptions)
      if (disconnect) {
        try {
          mqttClient.end()
          console.log('MQTT successfully disconnected!')
        } catch (error) {
          console.log('MQTT disconnect failed', error.toString())
        }
      }
      // mqtt连接
      mqttClient.on('connect', (e) => {
        if (!disconnect) {
          console.log("mqtt连接地址：", service);
          console.log(`mqtt连接成功：{clientId: ${clientOptions.clientId}}`)
          mqttClient.subscribe(topic, { qos: 0 }, (error) => {
            if (!error) {
              console.log(`主题订阅成功-${topic}`)
            } else {
              console.log(`主题订阅失败-${topic}`)
            }
          })
        }
      })

      // 消费消息
      mqttClient.on('message', (topic, message) => {
        let messageData = JSON.parse(message.toString())
        this.$emit('on-message', topic, messageData)
      })

      // 断开发起重连
      mqttClient.on('reconnect', (error) => {
        console.log('正在重连:', error)
      })
      // 链接异常处理
      mqttClient.on('error', (error) => {
        console.log('连接失败:', error)
      })

    },
  },

  destroyed() {
    this.mqttController(this.service, this.username, this.password, this.topic, true)
  },
}

</script>
<style lang='scss' scoped>
</style>